package edu.pku.sei.transformation.qvt.action;

import java.io.FileWriter;
import java.io.IOException;

import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

import edu.pku.sei.transformation.editor.model.AtomicTransformation;
import edu.pku.sei.transformation.editor.views.icons.IconsProvider;
import edu.pku.sei.transformation.qvt.adapter.standardqvt.TransformationAdapter;
import edu.pku.sei.transformation.qvt.codegen.QVTGenerator;

public class GenQVTAction extends Action {
	private AtomicTransformation transformation = null;

	public GenQVTAction(Object obj) {
		setText("generate standard qvt");
		setImageDescriptor(IconsProvider
				.getImageDescriptor(IconsProvider.FILE_EXPORT_ICO));
		if (obj instanceof AtomicTransformation)
			transformation = (AtomicTransformation) obj;
	}
	
	@Override
	public boolean isEnabled() {
		if (transformation != null)
			return true;
		else
			return false;
	}

	@Override
	public void run() {
		Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
				.getShell();
		FileDialog dialog = new FileDialog(shell, SWT.SAVE);
		dialog.setFileName(transformation.getName() + ".qvt");
		String addr = dialog.open();
		if (addr == null)
			return;
		QVTGenerator generator = new QVTGenerator();
		String content = generator.generate(new TransformationAdapter(
				transformation));

		FileWriter fw;
		try {
			fw = new FileWriter(addr);
			fw.write(content, 0, content.length());
			fw.flush();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
